// Do not remove the include below
#include "RF4RelayController.h"

#include "RFReceiverModule.h"
#include <Streaming.h>
#include <MsTimer2.h>
//#include "Arduino.h"
#include "HardwareSerial.h"
#include <MemoryFree.h>
#define MAX_COMMANDS (sizeof(commands)/sizeof(String))

int c = 0;

String sBuffer;

extern HardwareSerial Serial;
Relay relays[NUM_RELAYS];
int keepOnID = -1;
ReceiverModule *receiverM;

void turnOff() {
	MsTimer2::stop();
	relays[keepOnID].turnOff();
}

void setup() {
	Serial.begin(115200);
	Serial << "Booting...";

	relays[0] = Relay(PORT_0);
	relays[1] = Relay(PORT_1);
	relays[2] = Relay(PORT_2);
	relays[3] = Relay(PORT_3);

//	vw_set_rx_pin(PORT_RF);
//	vw_setup(4000); // Bits per sec
//	vw_rx_start(); // Start the receiver PLL running
	receiverM = (ReceiverModule*) new RFReceiverModule(2, 4000);
	delay(500);
	Serial << " OK" << endl;
//	MsTimer2::set(5000, turnOff);
}

void loop() {

	Message message = receiverM->receiveMessage();
	Serial << "Received message: " << message.getContent() << endl;
	Message msg = message.getContent();
	if (msg.getContent() != NULL) {
		Command command = Command::parseCommand(message.getContent());
		execute(command);
	}

	delay(100);
	Serial << "--          --" << endl;
}

void execute(Command command) {
	int relayID = command.getInteger(0);
	if (relayID>0&&relayID<=4) {
		Relay* relay = &relays[relayID - 1];
		Serial << command.getName() << "(" << relayID << ")" << endl;
		if (relayID != -1) {
			if (command.getName().equals(TURN_ON_CMD)) {
				relay->turnOn();
			} else if (command.getName().equals(TURN_OFF_CMD)) {
				relay->turnOff();
			} else if (command.getName().equals(SWITCH_CMD)) {
				if (relay->getState()) {
					relay->turnOff();
				} else {
					relay->turnOn();
				}
			} else if (command.getName().equals(KEEP_ON_CMD)) {
				int time = command.getInteger(1);
				MsTimer2::set(time * 1000, turnOff);
				relay->turnOn();
				keepOnID = relayID;
				MsTimer2::start();
			}
		}
	}

}

